
#include "StdAfx.h"
#include "BitField.h"
#include <string.h>

BitField::BitField( unsigned int* buffer, unsigned int size ){
	isExtern_ = true;
	machine_bit_ = ( sizeof( size_t ) * DEF_BIT_PER_BYTE );
	real_array_size_ = size / sizeof( size_t );
	bits_ = buffer;	
}

BitField::BitField( unsigned int count ){
	if(! count )
		return;

	isExtern_ = false;
	count++;
	machine_bit_ = ( sizeof( size_t ) * DEF_BIT_PER_BYTE );
	real_array_size_ = ( count + (machine_bit_ - 1) ) / machine_bit_;
	bits_ = new unsigned int[real_array_size_];
	reset();
}

BitField::~BitField(){
	if(! isExtern_ )
		SAFE_DELETE_ARRAY( bits_ );
}

void BitField::reset(){
	memset( bits_, 0, sizeof( size_t ) * real_array_size_ );
}

bool BitField::isOn( unsigned int idx ){
	if(! idx )
		return false;

	size_t array_idx = getArrayIdx( idx );
	size_t point_value = getPointValue( idx );

	if( bits_[ array_idx ] & point_value )
		return true;
	return false;
}

void BitField::setOn( unsigned int idx ){
	if(! idx )
		return;

	size_t array_idx = getArrayIdx( idx );
	size_t point_value = getPointValue( idx );

	bits_[ array_idx ] |= point_value;
}

void BitField::setOff( unsigned int idx ){
	if(! idx )
		return;

	size_t array_idx = getArrayIdx( idx );
	size_t point_value = getPointValue( idx );

	bits_[ array_idx ] &= ~point_value;
}

unsigned int BitField::getArrayIdx( unsigned int value ){
	if( value == 0 )
		return 0;

	return value / machine_bit_;
}

unsigned int BitField::getPointValue( unsigned int value ){
	if(! value )
		return 0;
	
	return (1 << (value % machine_bit_) );
}
